﻿//-----------------------------------------------------------------------
// <copyright file="ComponentModule.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace App.Modules.Component
{
    using System.Collections.Generic;
    using System.Threading;
    using App.Exceptions;
    using App.Modules.Package;
    using TileTool.Action;
    using TileTool.Base.Component;
    using TileTool.Component;
    using TileTool.Log;
    using TileTool.Message;
    using TileTool.Render;
    using TileTool.Scene;
    using TileTool.Scene.Entity;
    using TileTool.Settings;
    using TileTool.Threading.Future;
    using TileTool.Tool;

    /// <summary>
    /// Application component module.
    /// </summary>
    public class ComponentModule : Module
    {
        #region Constants - Private

        /// <summary>
        /// Log message group.
        /// </summary>
        private const string LogGroup = "ComponentModule";

        #endregion

        #region Fields - Private

        /// <summary>
        /// Component provider used by the module.
        /// </summary>
        private IComponentProvider provider;

        #endregion

        #region Methods - Public

        /// <summary>
        /// Called when the application is starting up.
        /// </summary>
        public override void Startup()
        {
            LogSystem.LogStartup(LogGroup, "Starting...");

            this.provider = new ComponentProvider();

            this.CollectComponents();

            base.Startup();
        }

        /// <summary>
        /// Called when the application is shutting down.
        /// </summary>
        public override void Shutdown()
        {
            base.Shutdown();
        }

        /// <summary>
        /// Given a component alias and a type, get the component from the component
        /// provider.
        /// 
        /// If the component is not found, an AppException exception will be thrown.
        /// </summary>
        /// <typeparam name="T">Component type to find.</typeparam>
        /// <param name="alias">Alias of the component to find.</param>
        /// <returns>Returns the component.</returns>
        public T Get<T>(string alias) where T : class, IComponent
        {
            PackageModule packageModule = GetModule<PackageModule>();
            string name = packageModule.GetComponentName(alias);

            T component = this.FindComponentInternal<T>(name);
            if (component == null)
            {
                throw new AppException("Unable to find component with alias and name: " + alias + " - " + name);
            }

            return component;
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Given a name and a type, find the component in the component
        /// provider.
        /// 
        /// If a component is not found, will throw an exception.
        /// </summary>
        /// <typeparam name="T">Component type to find.</typeparam>
        /// <param name="name">Name of the component to find.</param>
        /// <returns>Returns the component or throws an exception if the component was not found.</returns>
        private T FindComponentInternal<T>(string name) where T : class, IComponent
        {
            return this.provider.GetComponentByName<T>(name);
        }

        /// <summary>
        /// Collect all components that we know about.
        /// </summary>
        private void CollectComponents()
        {
            LogSystem.LogStartup(LogGroup, "Collecting components...");

            AutoResetEvent waitEvent = new AutoResetEvent(false);
            IFuture future = this.provider.Collect();

            future.OnComplete((IFuture completed) => waitEvent.Set());

            waitEvent.WaitOne();
        }

        #endregion
    }
}
